/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sd_proj1.mainProgram;

import sd_proj1.interfaces.IClient;
import sd_proj1.interfaces.IntClientesFifo;

/**
 *
 * @author PedroEee
 */
class Cliente extends Thread {

	/**
	 *  Identificação do artesao
	 *
	 *    @serialField clienteId
	 */
	private int clienteId;
	/*
	 *  Oficina
	 *
	 *    @serialField oficina
	 */
	private IClient loja;
	private IntClientesFifo req;

	/**
	 *  Instanciação do thread artesao.
	 *
	 *    @param clienteId identificação do artesao
	 *    @param MonitorOficina oficina
	 */
	public Cliente(int clienteId, IClient loja, IntClientesFifo req) {
		this.clienteId = clienteId;
		this.loja = loja;
		this.req = req;
	}

	@Override
	public void run() {
		int ng;                              /* number of selected goods */
		while (!loja.endOperCustomer(clienteId)) {
			while (true) {
				livingNormalLife();           /* the customer minds his own business */
				loja.goShopping(clienteId);                  /* the customer decides to visit the
				handicraft shop */
				if (loja.isDoorOpen()) /* the customer checks if the shop door is open */ {
					break;                                                    /* it is */
				} else {
					if (loja.isDonaIsDead()) {
						break;
					} else {
						tryAgainLater();       /* it is not, the customer goes back to perform his daily chores */
					}
				}
			}
			if (!loja.isDonaIsDead()) {
				loja.enterShop(clienteId);        /* the customer enters the shop */

				ng = loja.perusingAround(clienteId);  /* the customer inspects the offer in display
				and eventually picks up some goods */

				if (ng != 0) {
					req.addRequestCliente(clienteId);
					loja.iWantThis(clienteId, ng);             /* the customer queues by the counter
					to pay for the selected goods */
				}
				loja.exitShop(clienteId);                           /* the customer leaves the shop */
			}
		}
	}

	/**
	 *  O cliente vivendo a vida normal (operação interna).
	 */
	private void livingNormalLife() {
		try {
			sleep((long) (1 + 40 * Math.random()));
		} catch (InterruptedException e) {
		}
		System.out.println("Vivendo " + clienteId);
	}

	/**
	 *  O cliente volta mais tarde à loja (operação interna).
	 */
	private void tryAgainLater() {
		try {
			sleep((long) (1 + 10 * Math.random()));
		} catch (InterruptedException e) {
		}
		System.out.println("EXPERIMENTA MAIS TARDE " + clienteId);
	}
}
